package com.pany.rememberpass;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;

public class MainActivity extends AppCompatActivity {
    private static final int RESULT_CODE_TAKE = 1;
    private static final int LOCAL_IMAGE_CODE = 2;
    private static final String TAG = "TAG";
    private TextView tv_wlc;
    private ImageView iv_icon;
    private Uri imageUri;
    private SharedPreferences spfRecorid;
    private SharedPreferences.Editor editor;

    @SuppressLint("CommitPrefEdits")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv_wlc = findViewById(R.id.tv_wlc);
        iv_icon = findViewById(R.id.iv_icon);
        Intent intent = getIntent();
        String stringExtra = intent.getStringExtra("phone");
        spfRecorid = getSharedPreferences("spfRecorid", MODE_PRIVATE);
        tv_wlc.setText("wlecome:" + stringExtra);

        if (editor == null) {
            editor = spfRecorid.edit();
            String image = spfRecorid.getString("image", "");
            if (!(image.equals(""))) {
                Bitmap bitmap = ImageUtil.base64ToImage(image);
                iv_icon.setImageBitmap(bitmap);
            }
        }

    }

    //退出頁面
    public void onClickLogOut(View view) {
        SharedPreferences sharedPreferences = getSharedPreferences("spfRecorid", MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putBoolean("isLogin", false);
        edit.apply();
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                doTake();
            } else {
                Toast.makeText(MainActivity.this, "没有打开权限", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == 2) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                OpenAlbum();
            } else {
                Toast.makeText(MainActivity.this, "没有打开相册权限", Toast.LENGTH_SHORT).show();
            }
        }


    }

    public void onClickXiangJi(View view) {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED) {

            doTake();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
        }

    }

    private void doTake() {
        File file = new File(getExternalCacheDir(), "imageOut.jpeg");
        if (file.exists()) {
            file.delete();
        }
        try {
            file.createNewFile();

        } catch (IOException e) {
            e.printStackTrace();
        }

        if (Build.VERSION.SDK_INT > 24) {
            // contentprovider
            imageUri = FileProvider.getUriForFile(this,
                    "com.pany.rememberpass.fileprovider", file);

        } else {
            imageUri = Uri.fromFile(file);
        }
//        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 启动系统相机
        Intent intent = new Intent();
        intent.setAction("android.media.action.IMAGE_CAPTURE");
//        intent.setAction("android.media.action.VIDEO_CAPTURE");
        //android.media.action.VIDEO_CAPTURE。录像
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

        if (intent.resolveActivity(getPackageManager()) != null) {
//            startActivity(intent);
            startActivityForResult(intent, 1);
        } else {
            Toast.makeText(this, "请先去启动系统相机！", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_CODE_TAKE) {
            if (resultCode == RESULT_OK) {
                ContentResolver contentResolver = getContentResolver();
                // 获取照片
                try {
                    //iamgePath =  /storage/emulated/0/DCIM/Camera/IMG_20220508_215251.jpg
                    //content://com.pany.rememberpass.fileprovider/image_path/Android/data/com.pany.rememberpass/cache/imageOut.jpeg
                    Log.d(TAG, "handleImageOnApi19:  -----------imageUri =" + imageUri);

                    InputStream inputStream = contentResolver.openInputStream(imageUri);
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    iv_icon.setImageBitmap(bitmap);
                    String s = ImageUtil.imageToBase64(bitmap);
                    spfRecorId(s);

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        } else if (requestCode == LOCAL_IMAGE_CODE) {
//            if (resultCode == 2) {
            if (resultCode == -1) {
                String path = null;

                if (Build.VERSION.SDK_INT < 19) {
                    Uri dataUri = data.getData(); // API 19 ,4.0 可以这样
                    path = getIamgePath(path, dataUri);
                    displayIamge(BitmapFactory.decodeFile(path));

                } else {
                    handleImageOnApi19(data);
                }

                if (path != null) {
                    Bitmap bitmap = BitmapFactory.decodeFile(path);
                    displayIamge(bitmap);
                }
            }
        }
    }

    private String getIamgePath(String path, Uri dataUri) {

        // 数据库下标
        Cursor cursor = getContentResolver().query(dataUri, null, path, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);

                Log.d(TAG, "getIamgePath: -----------columnIndex =" + columnIndex);
                Log.d(TAG, "getIamgePath: --------------cursor =" + cursor);
                path = cursor.getString(columnIndex);
            }
            cursor.close();

        }
        return path;
    }

    private void displayIamge(Bitmap bitmap) {

        iv_icon.setImageBitmap(bitmap);
        String s = ImageUtil.imageToBase64(bitmap);
        spfRecorId(s);
    }

    private void spfRecorId(String s) {
        editor = spfRecorid.edit();
        editor.putString("image", s);
        editor.apply();
    }


    @TargetApi(19)
    private void handleImageOnApi19(Intent data) {

        String iamgePath = null;
        Uri dataUri = data.getData();

        Log.d(TAG, "handleImageOnApi19:  -----------dataUri =" + dataUri);

        if (DocumentsContract.isDocumentUri(this, dataUri)) {
            String documentId = DocumentsContract.getDocumentId(dataUri);

            if (TextUtils.equals(dataUri.getAuthority(), "com.android.providers.media.documents")) {
                String id = documentId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;

                dataUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                iamgePath = getIamgePath(selection, dataUri);


                Log.d(TAG, "handleImageOnApi19: selection = " + selection);

            } else if (TextUtils.equals(dataUri.getAuthority(), "com.android.providers.downloads.documents")) {

                Uri uri = ContentUris.withAppendedId(Uri.parse("content://dowloads/public_downloads"), Long.valueOf(documentId));

                iamgePath = getIamgePath(null, uri);  //  肯能会有问题
            }
        } else if ("content".equalsIgnoreCase(dataUri.getScheme())) {
//            iamgePath = getIamgePath(null, dataUri);

            iamgePath = uriParse(this, dataUri);

            //iamgePath =  /storage/emulated/0/DCIM/Camera/IMG_20220508_215251.jpg
            Log.d(TAG, "getIamgePath: 246----------------iamgePath =  " + iamgePath);
            Log.d(TAG, "getIamgePath: 246----------------dataUri =  " + dataUri);
            return;
        } else if ("file".equalsIgnoreCase(dataUri.getScheme())) {
            iamgePath = dataUri.getPath();
        }

        displayIamge(ImageUtil.base64ToImage(iamgePath));
    }


    @SuppressLint("Range")
    private String uriParse(Context context, Uri uri) {


        String path = null;

        File file = new File(getCacheDir(), "temp_file" +
                getContentResolver().getType(uri).split("/")[1]);

        InputStream inputStream = null;
        try {
            inputStream = getContentResolver().openInputStream(uri);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            byte[] buffer = new byte[4 * 1024];
            int resd;
            while ((resd = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, resd);

            }
            fileOutputStream.flush();

            Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());

            displayIamge(bitmap);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    //点击打开相册
    public void onClickAlbum(View view) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            OpenAlbum();

        } else {
            //打开权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 2);

        }

    }

    private void OpenAlbum() {
        Intent intent = new Intent();
        /* 开启Pictures画面Type设定为image */
        intent.setType("image/*");
        /* 使用Intent.ACTION_GET_CONTENT这个Action */
        intent.setAction(Intent.ACTION_PICK);
        /* 取得相片后返回本画面 */
        startActivityForResult(intent, LOCAL_IMAGE_CODE);
    }

    public void onClickJumpListview(View view) {

        Intent intent = new Intent(this, SimpleActivity.class);
        startActivity(intent);
    }

    public void onClickBaseAdapter(View view) {
        Intent intent = new Intent(this, SimpleActivity.class);
        startActivity(intent);
    }

    public void onClickRecycler(View view) {
        Intent intent = new Intent(this, RecyclerViewActivity.class);
        startActivity(intent);
    }

    public void onClickINTERNET(View view) {
        Intent intent = new Intent(this, InternetViewActivity.class);
        startActivity(intent);
    }

    public void onClickGotoViewpager(View view) {
        Intent intent = new Intent(this, ViewpagerActivity.class);
        startActivity(intent);

    }
}